package com.topteam.frame.entity;

import java.util.List;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.ModelBean;
import com.jfinal.plugin.activerecord.Page;
import com.topteam.utility.StringUtil;

@ModelBean("FrameDept")
public class FrameDept extends Model<FrameDept> {

	private static final long serialVersionUID = -3743632753274581081L;
	public static final FrameDept dao = new FrameDept();

	public List<FrameDept> getRootDept() {
		String sql = "select t.* from FrameDept t where t.parentId is null or t.parentId='' order by t.order desc";
		return find(sql);
	}

	public List<FrameDept> getAllDept() {
		String sql = "select t.* from FrameDept t order by t.order desc";
		return find(sql);
	}

	public Page<FrameDept> getDeptPage(int page, int size) {
		return paginate(page, size, "select t.*",
				"from FrameDept t order by t.order desc");
	}

	public Page<FrameDept> getDeptsByCode(String code, int page, int size) {
		return paginate(page, size, "select t.*",
				"from FrameDept t where t.deptCode like '" + code
						+ "%' order by  t.order desc");
	}

	public String getNextCode(String parentId) {
		String sql = null;
		String parentCode = "";
		if (StringUtil.isNull(parentId)) {
			sql = "select max(deptCode) from FrameDept t where LENGTH(t.deptCode)=4 ";
		} else {
			FrameDept parent = findById(parentId);
			parentCode = parent.getStr("deptCode");
			if (StringUtil.isNull(parentCode)) {
				sql = "select max(deptCode) from FrameDept t where LENGTH(t.deptCode)=4 ";
			} else {
				int length = parentCode.length();
				sql = "select max(deptCode) from FrameDept t where t.parentId = '"
						+ parentId
						+ "' AND LENGTH(t.deptCode)="
						+ (length + 4)
						+ " and substring(t.deptCode,1,"
						+ length
						+ ")='"
						+ parentCode + "'";
			}
		}
		String code = Db.queryStr(sql);
		if (code == null) {
			return parentCode + "0001";
		} else {
			return StringUtil.nextCode(code);
		}
	}

	public void deleteIds(String ids) {
		String[] id = ids.split(";");
		for (int i = 0; i < id.length; i++) {
			deleteById(id[i]);
			
			// 同时删除部门人员关系
			UserDeptRelation.dao.deleteUserDeptRelationByDetpId(id[i]);
		}
	}

	public void updateSubCode(FrameDept d, String newCode) {
		String code = d.getStr("deptCode") == null ? "" : d.getStr("deptCode");

		List<FrameDept> list = find("select * from FrameDept where deptCode like '"
				+ code + "%'");
		for (int i = 0; i < list.size(); i++) {
			FrameDept fd = list.get(i);
			fd.set("deptCode",
					newCode + fd.getStr("deptCode").substring(code.length()));
			fd.update();
		}
	}
	
	public boolean hasChild(String id){
		String sql ;
		if(StringUtil.isNull(id)){
			sql = "select count(*) from FrameDept where parentId is null";
		}else{
			sql = "select count(*) from FrameDept where parentId='"+id+"'";
		}
		long count = Db.queryLong(sql);
		return count>0;
	}
}
